<?php


namespace App\Http\Controllers\ums;

use App\Common\Components\ApiController;
use App\Models\Role;
use App\Models\RoleMenuRelation;
use Illuminate\Support\Facades\DB;

class RoleController extends ApiController
{
    
    public function listAll(){
        $record = Role::get();
        return $this->successJson('操作成功',$record);
    }

    public function list(){
        $record = Role::paginate(10);
        return $this->successJson('操作成功',$record);
    }

    public function updateStatus(){
        $param = request()->input();
        $role_id = $param['id'];
        $status = $param['status'];
        $role = Role::where('id',$role_id)->first();
        $role->status = $status;
        $role->save();
        return $this->successJson();
    }

    public function update(){
        $param = request()->input();
        $role_id = $param['id'];
        $role = Role::where('id',$role_id)->first();
        $role->name = $param['name'];
        $role->description = $param['description'];
        $role->admin_count = $param['admin_count'];
        $role->status = $param['status'];
        $role->sort = $param['sort'];
        $role->save();
        return $this->successJson();
    }

    
    public function create(){
        $param = request()->input();
        $role = new Role();
        $role->fill($param);
        $now = new \DateTime();
        $role->create_time = $now;
        $role->save();
        return $this->successJson();
    }

    public function delete(){
        $param = request()->input();
        $role_id = $param['id'];
        Role::where('id', $role_id)->delete();
        return $this->successJson();
    }

    public function allocMenu(){
        $param = request()->input();
        $RoleMenuRelation = RoleMenuRelation::where('role_id', $param['roleId'])->first();
        if($RoleMenuRelation){
            $RoleMenuRelation->menu_code = $param['menuCodes'];
            $RoleMenuRelation->save();
        }else{
            RoleMenuRelation::create([
                'role_id' => $param['roleId'],
                'menu_code' =>$param['menuCodes'],
            ]);
        }
        return $this->successJson();
    }

    public function listMenu(){
        $param = request()->input();
        $role_id = $param['roleId'];
        $RoleMenuRelation = RoleMenuRelation::where('role_id', $role_id)->first();
        $menuCodes = explode(",", $RoleMenuRelation->menu_code);
        return $this->successJson('',$menuCodes);
    }
}